package topevery.syn.data.model.codec;

import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;

import java.io.IOException;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeCodec implements ObjectSerializer, ObjectDeserializer {

    private static final String pattern = "yyyy-MM-dd HH:mm:ss";

    private static final String patternfff = "yyyy-MM-dd HH:mm:ss.fff";

    @Override
    public <T> T deserialze(DefaultJSONParser defaultJSONParser, Type type, Object o) {
        Object obj = defaultJSONParser.parse();
        String txt = obj.toString();
        String patternT = txt.indexOf(".") >= 0 ? patternfff : pattern;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(patternT);
        return obj == null ? null : (T) LocalDateTime.parse(obj.toString(), formatter);
    }

    @Override
    public int getFastMatchToken() {
        return 0;
    }

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        LocalDateTime localDateTime = (LocalDateTime) object;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        String txt = formatter.format(localDateTime);
        serializer.write(txt);
    }
}